package com.bawei.library_network.interceptor

import com.bawei.library_network.factory.ApiResponse
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.nio.charset.Charset

/**

 * @Author : ytx

 * @Time : On 2023/5/20 10:57

 * @Description : TokenInterceptor

 */
class TokenInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        //1:从本地获得accessToken和refreshToken
        val accessToken = SPUtils.getInstance().getString("access_token")
        val refreshToken = SPUtils.getInstance().getString("refresh_token")
        //2：添加access_token请求头完成网络请求
        var request = chain.request().newBuilder().addHeader("access_token",accessToken).build()
        var response = chain.proceed(request)
        //3:判断accessToken是否过期
        if(isTokenExpired(response)){//access_token过期
            //4：根据refreshToken访问api接口获得新的token本地更新
            var newToken = getNewToken(refreshToken)
            //5：使用新的Token，创建新的请求并发起请求
            request = chain.request().newBuilder().addHeader("access_token",newToken).build()
            response = chain.proceed(request)
        }
        return response

        //6：业务端若还失败，refreshToken也过期，跳转到登陆页面
    }

    //解决并发问题
    @Synchronized
    private fun getNewToken(refresh_token:String):String{
        /*访问特定的api接口获得新的accessToken和refreshToken*/
        /*成功，refresh_token没有过期:返回accessToken+更新本地的accessToken和refreshToken保存*/
        /*失败，refresh_token过期：返回""*/

//        Retrofit retrofit= new Retrofit.Builder()
//            /*API的主机地址*/
//            .baseUrl("https://url")
//            .addConverterFactory(GsonConverterFactory.create())
//            .build();
//        retrofit2.Response<JsonObject> requestToken = retrofit.create(ApiProtocol.class).DriverLogin().execute();
//        /*生成新的token*/
//        String token=requestToken.body().get("Token").toString();
//        /*需要更新本地的token保存*/

        return "xindeaccessToken"

    }

    //判断token是否过期
    private fun isTokenExpired(response: Response): Boolean {
        try {
            val responseBody = response.body()
            val source = responseBody!!.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer
            val utf8 = Charset.forName("UTF-8")
            val string: String = buffer.clone().readString(utf8)
            val apiResponse = Gson().fromJson(string, ApiResponse::class.java)
            if (apiResponse.code == 1) return true
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return false
    }

}